package com.example.demo.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.custom.BaseController;
import com.example.demo.entity.Permission;
import com.example.demo.form.PermissionForm;
import com.example.demo.service.PermissionService;

@Controller
@RequestMapping(value = "/permission")
public class PermissionController extends BaseController<Permission, Integer, PermissionForm>{
	
	@Autowired
	private PermissionService service;
	

	
	@SuppressWarnings("serial")
	@Override
	public Specification<Permission> buildSpec(PermissionForm form) {
		Specification<Permission> spec=new Specification<Permission>() {
			@Override
			public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String code = form.getCode();
				if(StringUtils.hasText(code)) {
					rules.add(cb.like(root.get("code"), "%"+code+"%"));
				}
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String search = form.getSearch();
				if(StringUtils.hasText(search)) {
					HashSet<Predicate> rules2=new HashSet<>();
					rules2.add(cb.like(root.get("name"), "%"+search+"%"));
					rules2.add(cb.like(root.get("code"), "%"+search+"%"));
					rules.add(cb.or(rules2.toArray(new Predicate[rules2.size()])));
				}
				
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	@Override
	public Object save(PermissionForm form) {
		Integer id = form.getId();
		if(id!=null) {
			Permission model = service.findById(id);
			String code = model.getCode();
			service.roleChangeCode(code, form.getCode());
			service.roleChangeName(model.getName(), form.getName());
		}
		return super.save(form);
	}
	
	
}
